package com.p2p.handler;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;
import java.util.regex.Pattern;

public class FixedUriRequestWrapper extends HttpServletRequestWrapper {
    // 待替换的非法字符：{ 和 }
    private static final Pattern ILLEGAL_CHARS_PATTERN = Pattern.compile("[{}]");
    private final String fixedUri;
    private final String fixedQueryString;

    public FixedUriRequestWrapper(HttpServletRequest request) {
        super(request);
        // 修复原始 URI 中的非法字符
        this.fixedUri = fixUri(request.getRequestURI());
        // 修复查询参数中的非法字符
        this.fixedQueryString = fixUri(request.getQueryString());
    }

    // 替换 { 为 %7B，} 为 %7D
    private String fixUri(String original) {
        if (original == null) return null;
        return ILLEGAL_CHARS_PATTERN.matcher(original)
                .replaceAll(match -> {
                    if (match.group().equals("{")) return "%7B";
                    else return "%7D";
                });
    }

    // 重写 URI 相关方法，返回修复后的值
    @Override
    public String getRequestURI() {
        return fixedUri;
    }

    @Override
    public String getQueryString() {
        return fixedQueryString;
    }

    /**
     * 修正 getRequestURL() 实现：返回 StringBuffer 类型
     */
    @Override
    public StringBuffer getRequestURL() {
        StringBuffer url = new StringBuffer();
        String scheme = getScheme();
        int port = getServerPort();
        if (port == -1) {
            port = 80; // 默认端口
        }

        url.append(scheme).append("://").append(getServerName());
        // 非标准端口需要显式拼接
        if ((scheme.equals("http") && port != 80) || (scheme.equals("https") && port != 443)) {
            url.append(":").append(port);
        }
        // 拼接修复后的 URI
        url.append(fixedUri);
        return url;
    }
}
